package mango.orm.oracle;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Date;

import mango.functions.FuncString;
import mango.orm.OrmException;
import mango.orm.impl.AbstractBinder;



public class OracleBinder extends AbstractBinder {
    public void bind(PreparedStatement statement, int index, Object val, int type)
            throws SQLException {
        if (index <= 0) {
            return;
        }
        if (val == null) {
            statement.setObject(index, null);
        }
        else if (val instanceof String) {
        	statement.setString(index, (String)FuncString.encodeIfString(val));
        }
        else if (val instanceof Integer || int.class == val.getClass()) {
        	statement.setInt(index, (Integer)val);
        }
        else if (val instanceof Date) {
            Date d = (Date) val;
            if (Types.DATE == type) {
                statement.setDate(index, new java.sql.Date(d.getTime()));
            }
            else {
                statement.setTimestamp(index, new Timestamp(d.getTime()));
            }
        }
        else if (val instanceof InputStream) {
            InputStream stream = (InputStream) val;
            try {
                Method md = statement.getClass().getMethod("setBlob", new Class[]{int.class, InputStream.class});
                md.invoke(statement, new Object[]{index, stream});
            }
            catch (Exception e) {
                try {
                    statement.setBinaryStream(index, stream, stream.available());
                }
                catch (IOException e2) {
                    throw new OrmException(e2);
                }
            }
//            statement.setBlob(index, (InputStream) val);
        }
        else {
            statement.setObject(index, val);
        }
    }
}
